package com.atguigu.realtime.app.dws;

import com.atguigu.realtime.udf.KeyWordProductUdtf;
import com.atguigu.realtime.udf.KeyWordUdtf;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.filesystem.FsStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.lang.reflect.Field;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/2/18 10:45
 */
public class DWSKeyWordStats4ProductApp {
    public static void main(String[] args) {
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        setWebUi(env, 2100);
        env.setParallelism(1);
        env.enableCheckpointing(5000, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointTimeout(60000);
        env
            .getCheckpointConfig()
            .enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        env.setStateBackend(new FsStateBackend("hdfs://hadoop162:8020/gmall2021/flink/checkpoint2"));
        
        final StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        
        // 1. 注册SourceTable: 从Kafka读数据  由于dws_product_stats聚合的时候已经有了窗口, 此处不用再开窗
        tenv.executeSql("CREATE TABLE product_stats (" +
                            "   spu_name STRING, " +
                            "   click_ct BIGINT," +
                            "   cart_ct BIGINT," +
                            "   order_ct BIGINT," +
                            "   stt STRING," +
                            "   edt STRING" +
                            ") WITH(" +
                            "   'connector' = 'kafka'," +
                            "   'topic' = 'dws_product_stats'," +
                            "   'properties.bootstrap.servers' = 'hadoop162:9029,hadoop163:9092,hadoop164:9092'," +
                            "   'properties.group.id' = 'DWSKeyWordStats4ProductApp'," +
                            "   'scan.startup.mode' = 'latest-offset'," +
                            "   'format' = 'json'" +
                            ")");
        
        // 2. 注册SinkTable: 向ClickHouse写数据
        tenv.executeSql("create table keyword_stats_2021(" +
                            "   stt string," +
                            "   edt string," +
                            "   keyword string," +
                            "   source string," +
                            "   ct bigint," +
                            "   ts bigint," +
                            "   PRIMARY KEY (stt, edt, keyword, source) NOT ENFORCED" +
                            ")with(" +
                            "   'connector' = 'clickhouse', " +
                            "   'url' = 'clickhouse://hadoop162:8123', " +
                            "   'database-name' = 'gmall2021', " +
                            "   'table-name' = 'keyword_stats_2021'," +
                            "   'sink.batch-size' = '100', " +
                            "   'sink.flush-interval' = '1000', " +
                            "   'sink.max-retries' = '3' " +
                            ")");
        
        // 3. 从SourceTable查询数据, 并写入到SinkTable
        // 3.1 注册自定义函数
        tenv.createTemporaryFunction("ik_analyze", KeyWordUdtf.class);
        tenv.createTemporaryFunction("KeyWordProduct", KeyWordProductUdtf.class);
        
        // 3.2 聚合计算
        final Table t1 = tenv.sqlQuery("select " +
                                           "    stt," +
                                           "    edt, " +
                                           "    keyword," +
                                           "    source, " +
                                           "    ct," +
                                           "    UNIX_TIMESTAMP()*1000 ts " +
                                           "from product_stats, " +
                                           "LATERAL TABLE(ik_analyze(spu_name)) as T(keyword) ," +
                                           "LATERAL TABLE(KeyWordProduct(click_ct,cart_ct,order_ct)) as T2(source, ct)");
        tenv.createTemporaryView("t1", t1);
        tenv.sqlQuery("select * from  t1").execute().print();
        
        // 3.3 数据写入到ClickHouse中  keyword_stats_2021
        tenv.executeSql("insert into keyword_stats_2021 select * from t1");
    }
    
    public static void setWebUi(StreamExecutionEnvironment env, int port) {
        try {
            final Field field = StreamExecutionEnvironment.class.getDeclaredField("configuration");
            field.setAccessible(true);
            final Configuration config = (Configuration) field.get(env);
            config.setInteger("rest.port", port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
